package com.wx.service.client.agentconfig.service.impl;

import com.wx.service.accesstoken.service.IAccessTokenService;
import com.wx.service.client.agentconfig.service.IWxAgentConfigService;
import com.wx.service.client.agentconfig.vo.WxAgentConfig;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;

@Service
public class WxAgentConfigServiceImpl implements IWxAgentConfigService {

  @Value("${wx.corpid}")
  private String corpid;

  @Value("${wx.aesKey}")
  private String aesKey;

  @Value("${wx.agent.accesstoken.url}")
  private String accessTokenUrl;

  @Value("${wx.agent.agengId}")
  private String agengId;

  @Value("${wx.agent.secret}")
  private String secret;

  @Value("${wx.agent.jsapiticket}")
  private String jsapiticketUrl;

  @Autowired
  private RestTemplate restTemplate;

  @Autowired
  private IAccessTokenService accessTokenService;

  @Override
  public WxAgentConfig getWxAgentConfig(String url) {
    String accessToken = accessTokenService.getAccessToken();
    String jsApiTicket = getJsApiTicket(accessToken);
    String noncestr = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    Long timestamp = System.currentTimeMillis();
    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

    String str1 = "jsapi_ticket=" + jsApiTicket +
        "&noncestr=" + noncestr +
        "&timestamp=" + timestamp +
        "&url=" + url;
    String signature = DigestUtils.sha1Hex(str1.getBytes());
    WxAgentConfig config = new WxAgentConfig();
    config.setAgentid(agengId);
    config.setCorpid(corpid);
    config.setNonceStr(noncestr);
    config.setTimestamp(timestamp);
    config.setSignature(signature);
    return config;
  }





  private String getJsApiTicket(String accessToken) {
    Map map = restTemplate.getForObject(jsapiticketUrl.replace("{accessToken}", accessToken), Map.class);
    return map.get("ticket").toString();
  }
}
